import React, {Component} from 'react';


import {
    View,
    StyleSheet,
    FlatList,
    TouchableOpacity,
    Text,
    Animated,
    ScrollView,
    Image,
    TouchableHighlight,
    TextInput, DeviceEventEmitter, ListView
} from 'react-native';
import StyleUtils from "../../../res/styles/StyleUtils";
import Navigation from "../../../custom/Navigation";
import ConfirmOrderListItem from "../../confirm/ConfirmOrderListItem";
import IparNetwork, {SERVER_TYPE} from "../../../httpUtils/IparNetwork";
import CommonUtils from "../../../common/CommonUtils";
import I18n from "../../../res/language/i18n";
import ModalBottomUtils from "../../../utils/ModalBottomUtils";
import ModalListUtils from "../../../utils/ModalListUtils";
import BottomSelectionBox from "../../../utils/BottomSelectionBox";
import ShippingMethodPage from "../../confirm/ShippingMethodPage";
import IparInput from "../../../custom/IparInput";
import AddressPage from "../../mePage/address/AddressPage";
import {KeyboardAwareScrollView} from "react-native-keyboard-aware-scroll-view";
import ViewUtils from "../../../utils/ViewUtils";
import IparImageView from "../../../custom/IparImageView";

const ds = new ListView.DataSource({
    rowHasChanged: (row1, row2) => row1 !== row2,
});


/**
 * g (get goods) = 获取产品方式
 * r (ReturnGoods) = 退货方式
 * @type {string}
 */
let bottomModalType = 'r';


/**
 * g = 获取的实体店
 * s = 退货的实体店
 * @type {string}
 */
let modalType = 's';


export default class ReturnGoodsOperation extends Component {

    constructor(props) {
        super(props);

        this.iparNetwork = new IparNetwork();

        this.goodsNum = (this.props.data && this.props.data.goods && this.props.data.goods.length) || 0;

        this.modalTitle = '';
        this.selectDeliveryType = null;//送货方式(自送/物流)
        this.selectReceiveType = null;//获取方式(自送/物流)
        this.selectSetWareHouse = null;//送的
        this.selectGetWareHouse = null;//获取的
        this.selectSetShippingData = null;//送货物流
        this.selectGetShippingData = null;//获取物流
        this.selectGetGoodsAddress = null;//获取地址
        this.logisticsNumber = '';

        this.state = {
            rotation: new Animated.Value(0),
            animHeight: new Animated.Value(120),

            wareHouseData: [],

            wareHouseGoodsData: [],//有产品

            modalVisible: false,
            bottomModalVisible: false,

            shippingAmount: 0//运费
        };
    }


    componentDidMount() {
        if (!this.props.data && !this.props.data.order_info) return;
        if (this.props.data.order_info.order_status === 24) {
            this.getWareHouseData();
        }
    }


    /**
     * 获取实体店数据
     */
    getWareHouseData() {

        CommonUtils.showLoading();
        this.iparNetwork.getRequest(SERVER_TYPE.adminIpar + 'getWareHouse?',
            'country=' + this.props.userInfo.country)
            .then((result) => {
                CommonUtils.dismissLoading();
                if (result.code === 200) {
                    this.setState({
                        wareHouseData: result.data,
                    });
                } else {
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                }
            })
            .catch((error) => {
                CommonUtils.dismissLoading();
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                console.log('ReturnGoodsOperation---getWareHouseData--error:' + error);
            });
    }

    /**
     * 获取实体店数据(产品有的。。)
     */
    getGoodsWareHouseData() {
        if (this.state.wareHouseGoodsData.length > 0) {
            this.modalTitle = 'wareHouse';
            modalType = 'g';
            this.setState({
                modalVisible: true
            });
            return;
        }

        let goodsData = [];
        for (goods of this.props.data.goods) {
            goodsData.push({
                "goods_id": goods.goods_id,
                "size": goods.goods_number
            });
        }
        let data = {
            "country": this.props.userInfo.country,
            "item": goodsData,
            "is_pickup": 1,
        };
        CommonUtils.showLoading();
        this.iparNetwork.getPostJson(SERVER_TYPE.goods + 'wareGoods?', data)
            .then((result) => {
                CommonUtils.dismissLoading();
                if (result.code === 200) {
                    this.modalTitle = 'wareHouse';
                    modalType = 'g';
                    this.setState({
                        modalVisible: true,
                        wareHouseGoodsData: result.data,
                    });
                } else {
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                }
            })
            .catch((error) => {
                CommonUtils.dismissLoading();
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                console.log('ReturnGoodsOperation---getGoodsWareHouseData--error:' + error);
            })
    }

    /**
     * 打开关闭动画
     */
    showGoodsAll() {
        let rotationValue = 1;
        let heightValue = 116 * this.goodsNum;
        if (this.isOpen) {
            rotationValue = 0;
            heightValue = 120;
        }
        Animated.timing(       // 随时间变化而执行的动画类型
            this.state.rotation,   // 动画中的变量值
            {
                toValue: rotationValue,   // 透明度最终变为1，即完全不透明
                duration: 500, // 动画时间
            }
        ).start();

        Animated.timing(       // 随时间变化而执行的动画类型
            this.state.animHeight,   // 动画中的变量值
            {
                toValue: heightValue,   // 透明度最终变为1，即完全不透明
                duration: 500, // 动画时间
            }
        ).start();

        this.isOpen = !this.isOpen;
    }


    /**
     * renderGoodsBox
     */
    renderGoodsBox() {
        return <View style={[styles.box,]}>

            <Animated.View
                style={{height: this.state.animHeight}}>
                <FlatList
                    style={{paddingLeft: 16, paddingRight: 16}}
                    renderItem={(item) => {
                        return <ConfirmOrderListItem
                            currencyInfo={{
                                currency_code: this.props.currencyCode,
                                swap_amount: this.props.swap_amount
                            }}
                            dataSource={item.item}/>
                    }}
                    data={this.props.data && this.props.data.goods || []}/>
            </Animated.View>
            {this.goodsNum > 1 && <TouchableOpacity
                activeOpacity={0.7}
                style={[{
                    height: 30,
                    position: "absolute",
                    bottom: 0,
                    left: 0,
                    right: 0,
                    backgroundColor: 'rgba(255,255,255,0.9)'
                }, StyleUtils.center]}
                onPress={() => this.showGoodsAll()}
            >
                <Animated.View
                    style={[{
                        transform: [{
                            rotateZ: this.state.rotation.interpolate({
                                inputRange: [0, 1],
                                outputRange: ['0deg', '180deg']
                            })
                        }],

                    }, StyleUtils.tabIconSize]}>
                    <Image
                        roundAsCircle={true}
                        style={[StyleUtils.tabIconSize, {tintColor: '#727476'},]}
                        source={require('../../../res/images/ic_more.png')}/>
                </Animated.View>

            </TouchableOpacity>}

        </View>
    }


    /**
     * renderKeyValueTextView
     * @returns {*}
     */
    renderKeyValueTextView(key, value, color) {
        return <View style={[StyleUtils.justifySpace, {paddingTop: 8, paddingBottom: 8, alignItems: null}]}>
            <Text style={[styles.text]}>{key}</Text>
            <Text style={[styles.text, {
                color: color || "gray",
                paddingLeft: 8,
                flex: 1,
                textAlign: 'right'
            }]}>{value}</Text>
        </View>
    }


    /**
     * renderSelectView
     * @param callBack
     * @param text
     * @param value
     * @returns {*}
     */
    renderSelectView(text, value, callBack) {
        return <View style={[StyleUtils.justifySpace, {marginTop: 16, alignItems: null}]}>

            <Text style={[StyleUtils.smallFont, styles.text]}>{text}</Text>

            <TouchableOpacity
                onPress={callBack}
                style={[StyleUtils.rowDirection, {
                    alignItems: 'center',
                    flex: 1,
                    marginLeft: 30,
                    justifyContent: 'flex-end'
                }]}>
                <Text style={[StyleUtils.smallFont, styles.text, {color: 'gray',}]}>{value}</Text>
                <Image
                    style={[styles.iconSize, {tintColor: 'gray', marginLeft: 8}]}
                    source={require('../../../res/images/ic_right_more.png')}/>
            </TouchableOpacity>
        </View>
    }


    /**
     * renderModalItem
     * @param rowData
     * @param index
     * @returns {*}
     */
    renderModalItem(rowData, index) {
        return <TouchableOpacity
            onPress={() => {
                if (modalType === 's') {
                    this.selectSetWareHouse = rowData;
                } else {
                    this.selectGetWareHouse = rowData;
                }
                this.setState({
                    modalVisible: false,
                });
            }}
            style={{padding: 8}}>
            <Text
                numberOfLines={2}
                style={[StyleUtils.smallFont, StyleUtils.title, {textAlign: null}]}>{rowData.name}</Text>
            <Text
                numberOfLines={2}
                style={[StyleUtils.smallFont, {fontSize: 12, color: 'gray'}]}>{rowData.address}</Text>
        </TouchableOpacity>
    }


    render() {
        let state = this.state;
        let data = this.props.data;
        let orderInfo = data.order_info;

        let statusIs24 = data.order_status === 24;//24可以操作

        return (
            <View style={[StyleUtils.flex, {backgroundColor: '#f3f3f3'}]}>
                <Navigation onClickLeftBtn={() => this.props.navigator.pop()}/>
                <View style={{backgroundColor: 'white', padding: 16, paddingTop: 0, paddingBottom: 6}}>
                    {this.renderKeyValueTextView(I18n.t('default.orderNo'), orderInfo.order_sn)}
                </View>
                {this.renderGoodsBox()}


                <KeyboardAwareScrollView>

                    <View style={[styles.box, {padding: 16, marginTop: 8,}]}>
                        {(data.return_type === 2 || data.return_type === 3) && this.renderKeyValueTextView(I18n.t('RT.refundAmount'), (this.props.data.return_amount).toFixed(2) + ' ' + this.props.currencyCode, 'red')}

                        {!(data.return_type === 2 || data.return_type === 3) && <Text style={[styles.text, {
                            color: "gray",
                            paddingLeft: 8,
                            marginTop: 20,
                            marginBottom: 20,
                        }]}>{I18n.t('RT.returnAmountMsj')}</Text>}
                        {this.renderKeyValueTextView(I18n.t('RT.returnType'), this.getReturnType(data.return_type))}
                        {(data.order_status === 21 || data.order_status === 22 || data.order_status === 25) && this.renderKeyValueTextView(I18n.t('default.status'), I18n.t('default.processing'))}


                        {!statusIs24 && <View style={[styles.box, {
                            paddingTop: 0,
                            marginTop: 8,
                            flexWrap: 'wrap',
                        }, StyleUtils.rowDirection]}>
                            {data.resion_img && data.resion_img.split(',').map((item, index) => {
                                console.log(item)
                                return <TouchableOpacity style={{marginRight: 16, marginTop: 16, height: 60}}>
                                    <IparImageView
                                        width={60}
                                        height={60}
                                        url={item}/>
                                </TouchableOpacity>
                            })}
                        </View>}


                        {statusIs24 && <View>


                            <View>
                                <Text
                                    style={[StyleUtils.smallFont, styles.text]}>{I18n.t('RT.returnAddress')}</Text>
                                <Text
                                    style={[StyleUtils.smallFont, {
                                        color: 'gray',
                                        fontSize: 14,
                                    }]}>{data.address}</Text>
                            </View>


                            {this.renderSelectView(I18n.t('RT.returnMethod'), this.selectDeliveryType !== null ? (I18n.t(this.selectDeliveryType === 1 ? 'RT.selfDeliver' : 'RT.logistics')) : '', () => {
                                bottomModalType = 'r';
                                this.setState({
                                    bottomModalVisible: true
                                });
                            })}

                            {/**Company address*/}
                            <View style={[{marginTop: 16}]}>

                                <Text style={[StyleUtils.smallFont, styles.text]}>{I18n.t('RT.returnAddress')}</Text>

                                <TouchableOpacity
                                    onPress={() => {
                                        if (this.selectDeliveryType === 1) {
                                            this.modalTitle = I18n.t('RT.warehouse');
                                            modalType = 's';
                                            this.setState({
                                                modalVisible: true
                                            });
                                        }
                                    }}
                                    style={[StyleUtils.justifySpace, {
                                        marginTop: 6,
                                        flex: 1,
                                        width: '100%'
                                    }]}>
                                    <Text style={[StyleUtils.smallFont, {
                                        color: 'gray',
                                        fontSize: 14,
                                        flex: 1,
                                    }]}>{this.selectDeliveryType === 0 ? data.address : this.selectSetWareHouse && this.selectSetWareHouse.address}</Text>
                                    <Image
                                        style={[styles.iconSize, {tintColor: 'gray', marginLeft: 8}]}
                                        source={require('../../../res/images/ic_right_more.png')}/>
                                </TouchableOpacity>
                            </View>


                            {this.selectDeliveryType === 0 && this.renderSelectView(I18n.t('RT.logisticsCompany'), this.selectSetShippingData && this.selectSetShippingData.name, () => {
                                this.props.navigator.push({
                                    component: ShippingMethodPage,
                                    name: 'ShippingMethodPage',
                                    params: {
                                        notCount: this.props.data.return_is_replace_shipping == 0,
                                        notShowPicup: true,
                                        countryShipping: this.props.userInfo.country,
                                        callback: (data) => {
                                            this.selectSetShippingData = data
                                        }
                                    }
                                });
                            })}


                            {this.selectDeliveryType === 0 &&
                            <IparInput
                                placeholder={I18n.t('RT.logisticsNumber')}
                                onChangeText={(text) =>
                                    this.logisticsNumber = text
                                }/>}


                            {data.return_type === 1 && this.renderSelectView(I18n.t('RT.receivingMethod'), this.selectReceiveType !== null ? (I18n.t(this.selectReceiveType === 1 ? 'RT.autologous' : 'RT.logistics')) : '', () => {
                                bottomModalType = 'g';
                                this.setState({
                                    bottomModalVisible: true
                                });
                            })}
                            {this.selectReceiveType !== null && this.renderSelectView(I18n.t('RT.receivingAddress'),
                                this.selectReceiveType === 1 ? this.selectGetWareHouse && this.selectGetWareHouse.address :
                                    this.selectGetGoodsAddress && this.selectGetGoodsAddress.address, () => {
                                    if (this.selectReceiveType === 1) {
                                        this.getGoodsWareHouseData();
                                    } else {
                                        this.props.navigator.push({
                                            component: AddressPage,
                                            name: 'AddressPage',
                                            params: {
                                                callback: (data) => {
                                                    this.selectGetGoodsAddress = data
                                                }
                                            }
                                        });
                                    }
                                })}
                            {this.selectReceiveType === 0 && this.renderSelectView(I18n.t('RT.logisticsCompany'), this.selectGetShippingData && this.selectGetShippingData.name, () => {
                                if (!this.selectGetGoodsAddress) {
                                    DeviceEventEmitter.emit('toast', I18n.t('RT.receivingAddress'));
                                    return;
                                }
                                this.props.navigator.push({
                                    component: ShippingMethodPage,
                                    name: 'ShippingMethodPage',
                                    params: {
                                        ...this.props,
                                        notCount: this.props.data.return_is_replace_shipping == 0,
                                        notShowPicup: true,
                                        dataSource: data.goods,
                                        shippingAddressData: this.selectGetGoodsAddress,
                                        origin: this.props.userInfo.country,

                                        callback: (data, resultData, shippingAmount) => {
                                            this.selectGetShippingData = data;
                                            let _shippingAmount = 0;
                                            if (data.expressService === 'china_post') {
                                                _shippingAmount = 10
                                            } else {
                                                _shippingAmount = shippingAmount
                                            }

                                            this.setState({
                                                shippingAmount: _shippingAmount
                                            });
                                        }
                                    }
                                });
                            })}
                            {data.return_is_replace_shipping === 1 && this.selectReceiveType === 0 && this.renderKeyValueTextView(I18n.t('default.shippingCost'), (this.state.shippingAmount).toFixed(2) + ' ' + this.props.currencyCode, 'red')}

                        </View>}
                    </View>

                </KeyboardAwareScrollView>


                {!(data.order_status === 21 || data.order_status === 22) && statusIs24 &&
                <View style={{padding: 16, backgroundColor: 'white'}}>
                    {ViewUtils.getButton(I18n.t('default.submit'), () => this.submit())}
                </View>}
                <ModalBottomUtils
                    visible={state.modalVisible}
                    renderRow={(rowData, s, index) => this.renderModalItem(rowData, index)}
                    requestClose={() => {
                        this.setState({modalVisible: false})
                    }}
                    dataSource={ds.cloneWithRows(modalType === 's' ? state.wareHouseData : state.wareHouseGoodsData)}
                    title={I18n.t('RT.selectWareHouse')}/>

                {/**Selection box */}
                <BottomSelectionBox
                    requestClose={() => {
                        this.setState({
                            bottomModalVisible: false,
                        })
                    }}
                    onClick={(type) => {
                        let result = 0;
                        if (type === 1) {
                            result = 1;
                        }
                        if (bottomModalType === 'r') {
                            this.selectDeliveryType = result;
                        } else {
                            this.selectReceiveType = result;
                        }
                        this.setState({
                            bottomModalVisible: false,
                        });
                    }}
                    textTop={I18n.t(bottomModalType === 'r' ? 'RT.selfDeliver' : 'RT.autologous')}
                    title={I18n.t(bottomModalType === 'r' ? 'RT.returnMethod' : 'RT.receivingMethod')}
                    textBottom={I18n.t('RT.logistics')}
                    visible={state.bottomModalVisible}
                />

            </View>
        );
    }


    /**
     * 0 正常  1 换货  2 退货退款 3 退款
     * getReturnType
     * return text
     */
    getReturnType(type) {
        let result = '';
        switch (type) {
            case 1:
                result = I18n.t('RT.exchangeGoods');
                break;
            case 2:
                result = I18n.t('RT.exchangeRefund');
                break;
            case 3:
                result = I18n.t('RT.refund');
                break;
        }
        return result;
    }


    /**
     * 提交
     */
    submit() {
        let data = this.props.data;
        let orderInfo = data.order_info;


        if (this.selectDeliveryType === null) {
            DeviceEventEmitter.emit('toast', I18n.t('RT.returnMethod'));
            return;
        }

        if (this.selectSetWareHouse === null && this.selectDeliveryType === 1) {
            DeviceEventEmitter.emit('toast', I18n.t('RT.returnMethod'));
            return;
        }


        let isSince = this.selectDeliveryType === 1;

        if (!isSince) {
            if (this.selectSetShippingData === null) {
                DeviceEventEmitter.emit('toast', I18n.t('RT.logisticsCompany'));
                return;
            }

            if (!this.logisticsNumber.trim()) {
                DeviceEventEmitter.emit('toast', I18n.t('RT.logisticsNumber'));
                return;
            }
        }

        let isReplace = data.return_type === 1;
        if (isReplace) {
            if (this.selectReceiveType === null) {
                DeviceEventEmitter.emit('toast', I18n.t('RT.receivingMethod'));
                return;
            }

            if (this.selectReceiveType === 1) {
                if (this.selectGetWareHouse === null) {
                    DeviceEventEmitter.emit('toast', I18n.t('RT.receivingAddress'));
                    return;
                }
            } else {
                if (!this.selectGetGoodsAddress) {
                    DeviceEventEmitter.emit('toast', I18n.t('RT.receivingAddress'));
                    return;
                }

                if (!this.selectGetShippingData) {
                    DeviceEventEmitter.emit('toast', I18n.t('RT.logisticsCompany'));
                    return;
                }

            }

        }


        CommonUtils.showLoading();

        let _return_warehouse_id = this.selectSetWareHouse ? this.selectSetWareHouse.warehouse_id : data.return_warehouse_id;
        let _return_warehouse_name = this.selectSetWareHouse ? this.selectSetWareHouse.name : data.return_warehouse_name;

        let formData = new FormData();
        //default
        formData.append('order_id', data.order_id);
        formData.append('refund_type', orderInfo.pay_type);
        formData.append('action_desc', 'dd');
        //return
        formData.append('return_is_pickup', this.selectDeliveryType);
        formData.append('return_warehouse_id', isSince ? _return_warehouse_id : null);
        formData.append('return_warehouse_name', isSince ? _return_warehouse_name : null);
        formData.append('return_express_id', isSince ? null : this.selectSetShippingData.id);
        formData.append('return_express_name', isSince ? null : this.selectSetShippingData.expressService);
        formData.append('return_logistics_number', this.logisticsNumber.trim());
        //get
        formData.append('replace_is_pickup', isReplace ? this.selectReceiveType : null);
        formData.append('replace_shipping_address_id', isReplace ? this.selectReceiveType === 1 ? this.selectReceiveType.warehouse_id : this.selectGetGoodsAddress.id : null);
        formData.append('replace_shipping_ammount', isReplace ? this.state.shippingAmount : null);
        console.log(formData);
        this.iparNetwork.getPostFrom(SERVER_TYPE.adminIpar + 'deliverGoods', formData)
            .then((result) => {
                CommonUtils.dismissLoading();
                if (result.code === 200) {
                    DeviceEventEmitter.emit('toast', I18n.t('default.success'));
                    this.props.navigator.popToTop();
                } else {
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                }
                console.log(result);
            })
            .catch((error) => {
                CommonUtils.dismissLoading();
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                console.log('ReturnGoodsOperation---submit--error:' + error);

            });
    }

}

const styles = StyleSheet.create({
    box: {
        backgroundColor: 'white',
    },

    text: {
        fontSize: 16,
    },
    iconSize: {
        width: 16,
        height: 16,
    },
});